﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Abstractions;
using Lrd.Template.Core.Infrastructure.Dependency;
using Lrd.Template.Core.Infrastructure.Extensions;

namespace Lrd.Template.Core.Infrastructure.Modules
{
    /// <summary>
    /// 模块管理器
    /// </summary>
    public class ModuleManager : IModuleManager
    {
        private readonly List<ModuleBase> _sourceModules;
        public IEnumerable<ModuleBase> SourceModules => _sourceModules;

        public IEnumerable<ModuleBase> LoadedModules { get; private set; }

        public ModuleManager()
        {
            _sourceModules = new List<ModuleBase>();
            LoadedModules = new List<ModuleBase>();
        }

        /// <summary>
        /// 加载模块
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceCollection LoadModules(IServiceCollection services)
        {
            //var moduleTypes1 = services.GetTypeFinder<IModuleBaseTypeFinder>(a=>new ModuleBaseTypeFinder(a)).FindAll()/* IocManage.Instance.GetService<IModuleBaseTypeFinder>().FindAll()*/;
            var moduleTypes = services.GetOrAddTypeFinder<IModuleBaseTypeFinder, ModuleBaseTypeFinder>().FindAll();
            _sourceModules.Clear();
            _sourceModules.AddRange(moduleTypes.Select(m => (ModuleBase)Activator.CreateInstance(m)));
            List<ModuleBase> modules = SourceModules.ToList();
            modules = modules.OrderBy(m => m.Order).ToList();
            LoadedModules = modules;

            foreach (var module in LoadedModules)
            {
                services = module.AddServices(services);
            }
            return services;
        }

        public void UsePack(IServiceProvider provider)
        {
            foreach (var module in LoadedModules)
            {
                module.UsePack(provider);
            }
        }
    }
}
